package com.party.mobile.web.controller.material;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.article.Article;
import com.party.core.model.article.ArticleType;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.system.*;
import com.party.core.service.article.IArticleService;
import com.party.core.service.commune.ICNotebookTypeService;
import com.party.core.service.member.IMemberGroupPermissionService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.system.IDictService;
import com.party.core.service.system.ISysRoleService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.activity.output.ActivityOutput;
import com.party.mobile.web.dto.article.output.ArticleListOutput;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @program: party
 * @description: 素材控制器
 * @author: Hua Qunhao
 * @create: 2019-12-11 14:02
 **/
@Controller
@RequestMapping(value = "/material")
public class MaterialController {
    @Autowired
    private CurrentUserBizService currentUserBizService;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IMemberGroupPermissionService memberGroupPermissionService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private IDictService dictService;
    @Autowired
    private ICNotebookTypeService notebookTypeService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 素材列表
     *
     * @param request
     * @param page    分页
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("getMaterialList")
    public AjaxResult getMaterialList(HttpServletRequest request, String materialType, Page page) {
        if (StringUtils.isEmpty(materialType)) {
            return AjaxResult.error(100, "参数为空");
        }
        try {
            String memberId = currentUserBizService.getCurrentUser(request).getId();
            HashMap<String, Object> params = new HashMap<>();
            boolean isTwoChild = sysRoleService.hasRoleType(memberId, RoleType.KNOWLEDGE_MANAGEMENT_ROLE);
            MemberGroup memberGroup = memberGroupService.get(memberId);
            if (isTwoChild) { //二级子账号
                List<String> targetIds = Lists.newArrayList();

                Integer isShowAll = memberGroupPermissionService.getIsShowAll(TargetType.MATERIAL.getCode(), memberId, memberGroup.getPartnerId(), targetIds);
                if (null == isShowAll) {
                    return AjaxResult.success(new ArrayList<ActivityOutput>(), page);
                } else if (YesNoStatus.NO.getCode().equals(isShowAll)) {
                    //分配了部分素材
                    params.put("ids", targetIds);
                } else {
                    //分配了该分社下的全部素材
                    params.put("member", memberGroup.getPartnerId());
                }
            } else {
                //是否为一级子账号
                boolean resutle = sysRoleService.hasRole(memberId, RoleEnum.ONE_LEVEL_CHILD.getCode());
                if (resutle) {
                    //该分社下的全部素材
                    params.put("member", memberId);
                } else {
                    //行知公社的全部素材
                    params.put("memberId", memberId);
                }
            }

            params.put("articleType", ArticleType.ARTICLE_TYPE_MATERIAL.getCode());
            params.put("materialType", materialType);
            List<Article> articleList = articleService.queryArticleList(params, page);
            if (!CollectionUtils.isEmpty(articleList)) {
                List<ArticleListOutput> outputList = LangUtils.transform(articleList, input -> {
                    ArticleListOutput output = ArticleListOutput.transform(input);
                    return output;
                });
                return AjaxResult.success(outputList, page);
            }
            return AjaxResult.success(Collections.EMPTY_LIST, page);
        } catch (Exception e) {
            logger.error("素材列表", e);
            return AjaxResult.error(100, "素材列表");
        }
    }


    /**
     * 编辑素材内容
     *
     * @param id      数据id
     * @param content 内容
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("updateMaterialContent")
    public AjaxResult updateMaterialContent(String id, String content) {
        try {
            Article article = articleService.get(id);
            if (article == null) {
                return AjaxResult.error(100, "素材不存在");
            }
            if (StringUtils.isEmpty(content)) {
                return AjaxResult.error(100, "素材内容不为空");
            }
            String content_val = StringUtils.unescapeHtml4Video2Iframe(content);
            article.setContent(content_val);
            articleService.update(article);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("编辑素材内容失败", e);
            return AjaxResult.error(100, "编辑素材内容失败");
        }
    }

    /**
     * @Description: 获取素材类型
     * @Param: []
     * @return: com.party.mobile.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/12/12
     */
    @ResponseBody
    @RequestMapping("getMaterialTypes")
    public AjaxResult getMaterialTypes() {
        try {
            // 素材类型
            Dict dict = new Dict();
            dict.setType(DictEnum.MATERIAL_TYPE.getCode());
            List<Dict> dicts = dictService.list(dict);
            List<HashMap<String, Object>> lists = new ArrayList<>();
            if (!CollectionUtils.isEmpty(dicts)) {
                lists = LangUtils.transform(dicts, input -> {
                    HashMap<String, Object> mmp = new HashMap<>();
                    mmp.put("fileName", input.getLabel());
                    mmp.put("materialType", input.getValue());
                    mmp.put("sort", input.getSort());
                    return mmp;
                });
            }
            return AjaxResult.success(lists);
        } catch (Exception e) {
            logger.error("编辑素材内容失败", e);
            return AjaxResult.error(100, "编辑素材内容失败");
        }
    }

    /**
     * 素材列表/new
     *
     * @param request
     * @param page    分页
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("new/getMaterialList")
    public AjaxResult getNewMaterialList(HttpServletRequest request, String notebookTypeId, Page page) {
        if (StringUtils.isEmpty(notebookTypeId)) {
            return AjaxResult.error(100, "参数为空");
        }
        try {
            HashMap<String, Object> params = new HashMap<>();
            params.put("articleType", ArticleType.ARTICLE_TYPE_MATERIAL.getCode());
            params.put("notebookTypeId", notebookTypeId);
            List<Article> articleList = articleService.queryArticleList(params, page);
            if (!CollectionUtils.isEmpty(articleList)) {
                List<ArticleListOutput> outputList = LangUtils.transform(articleList, input -> {
                    ArticleListOutput output = ArticleListOutput.transform(input);
                    return output;
                });
                return AjaxResult.success(outputList, page);
            }
            return AjaxResult.success(Collections.EMPTY_LIST, page);
        } catch (Exception e) {
            logger.error("素材列表", e);
            return AjaxResult.error(100, "素材列表");
        }
    }

    /**
     * 笔记本类型列表
     *
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("queryNotebookTypeList")
    public AjaxResult queryNotebookTypeList(HttpServletRequest request, Page page) {
        try {
            String memberId = currentUserBizService.getCurrentUser(request).getId();
            Map<String, Object> mmp = Maps.newHashMap();
            if(memberGroupService.isChild(memberId)){
                mmp.put("memberGroupUserId", memberId);
            }else{
                mmp.put("createBy", memberId);
            }
            List<Map<String, Object>> notebookTypes = notebookTypeService.mobileListPage(mmp, page);
            return AjaxResult.success(notebookTypes);
        } catch (Exception e) {
            logger.error("获取笔记本类型列表失败", e);
            return AjaxResult.error(100, "获取笔记本类型列表失败");
        }
    }
}
